package com.zsl.filter;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;

import javax.jms.Session;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

@WebFilter(filterName = "RoleFilter", urlPatterns = "/*")
public class RoleFilter implements Filter {
    public void destroy() {

    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
        String servletPath = request.getServletPath();
        //跳过静态文件
        //跳过登录与注册
        if (servletPath.endsWith("index.jsp") ||
                servletPath.endsWith(".map") ||
                servletPath.endsWith(".js") ||
                servletPath.endsWith(".css") ||
                servletPath.endsWith(".jpg") ||
                servletPath.endsWith(".png") ||
                servletPath.endsWith(".gif") ||
                //忽略登录注册页面
                servletPath.equals("/login") ||
                servletPath.equals("/register")) {
            chain.doFilter(request, response);
            //System.out.println(servletPath);
            return;
        }
        //判断是否拥有角色
        HttpSession session = request.getSession();
        String role = (String) session.getAttribute("role");
        if (role != null && (role.equals("admin") || role.equals("users"))) {
            chain.doFilter(request, response);
            //System.out.println(servletPath);
            return;
        }
        //没有角色返回错误的json，并重定向
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();
        Map<String, Object> result = new HashMap<>();
        result.put("code", 0);
        result.put("msg", "非法访问");
        out.write(JSON.toJSONString(result));
        response.sendRedirect("../bookstoreOnline/");
    }

    public void init(FilterConfig config) throws ServletException {

    }

}
